package com.lhg.framework.emq;

import com.lhg.config.EmqConfig;
import com.lhg.utils.uuid.UUID;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Emq连接客户端
 * @author 刘华桂
 */
@Component
@Slf4j
public class EmqClient {
    @Autowired
    private EmqConfig emqConfig;

    private MqttClient mqttClient;

    @Autowired
    private EmqMsgProcess emqMsgProcess;

    /**
     * 连接客户端
     */
    public void connect(){
        try {
            // 得到一个MQTT客户端
            //String serverURI服务url, String clientId客户端id
            mqttClient = new MqttClient(emqConfig.getMqttServerUrl(),
                    "monitor." + UUID.randomUUID().toString());
            // 设置一个消息进程对象挂载的客户端对象
            mqttClient.setCallback(emqMsgProcess);
            // 连接
            mqttClient.connect();
        } catch (MqttException e) {
            log.error("连接失败");
            e.printStackTrace();
        }

    }

    /**
     * 发布消息
     * @param topic 订阅主题
     * @param msg 发送的消息
     */
    public void publish(String topic,String msg){
        try {
            MqttMessage mqttMessage = new MqttMessage(msg.getBytes());
            mqttClient.getTopic(topic).publish(mqttMessage);
        } catch (MqttException e) {
            log.error("发布信息发生异常");
            e.printStackTrace();
        }
    }

    /**
     * 订阅主题
     * @param topicName topic名称
     * @throws MqttException MQTT异常
     */
    public void subscribe(String topicName) throws MqttException {
        mqttClient.subscribe(topicName);
    }
}
